Page({
    data: {
        scrollTop: "",
        inputValue: "",
        messages: [{
            id: 1,
            type: 'ChatGPT',
            text: '你好，我是 ChatGPT，有什么我可以帮助你的吗？'
        }]
    },
    handleInput(e) {
        this.setData({
            inputValue: e.detail.value
        })
    },

    sendMessage() {
        const userInput = this.data.inputValue.trim();
        if (userInput !== '') {
            this.createChat("user", userInput);

            this.setData({
                inputValue: ''
            })

            this.goToBottom()
            this.getAPI(userInput)
        }
    },

    createChat(type, message) {
        let newMessage = {
            id: this.data.messages.length + 1,
            type: type,
            text: message
        }
        this.setData({
            messages: [...this.data.messages, newMessage],
        });
    },

    // 滚动条
    goToBottom() {
        const query = wx.createSelectorQuery().in(this)
        // 获取节点信息
        // query.select(".conversation-bar").boundingClientRect()
        query.select(".scroll-view").boundingClientRect()

        query.exec(res => {
            // 获取滚动条的高度
            // const scrollHeight = res[0].height
            // 获取对话列表的高度
            // const listHeight = res[1].height

            this.setData({
                // scrollTop: scrollHeight - listHeight
                scrollTop:10000
            })
        })
    },

    // 获取后端接口
    getAPI(userInput) {
        wx.request({
            url: `http://localhost:8080/api/AI?message=${userInput}`,
            method: 'GET',
            // method: 'POST',
            success: res => {
                console.log(res);
                this.createChat('ChatGPT', res.data)
                this.goToBottom();
            }
        })
    }

});